package com.exartisan.thanhdoanhn;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.exartisan.adapter.EventAdapter;
import com.exartisan.bean.Event;
import com.exartisan.network.NetworkUtility;
import com.exartisan.network.NewNetworkUtility;
import com.exartisan.network.NewParamBuilder;
import com.exartisan.network.NewResponseTranslater;
import com.exartisan.network.NewRestConnector;
import com.exartisan.network.RestConnector;
import com.exartisan.util.DataHolder;
import com.exartisan.util.Util;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;

public class FragmentEvent extends SherlockFragment {
	ArrayList<Event> listEvents;
	ListView lvEvent;
	View footer;
	EventAdapter adapter;
	
	ProgressBar prBar;
	Button btnRetry;
	boolean isLoading;
	boolean isLastPage;
	int pageCount;
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_listevent, container, false);
        lvEvent=(ListView) rootView.findViewById(R.id.lvEvent);
        prBar = (ProgressBar) rootView.findViewById(R.id.pro_event);
        btnRetry = (Button) rootView.findViewById(R.id.btnRetryEvent);
        
        footer = inflater.inflate(R.layout.row_load_more, lvEvent, false);
        
        lvEvent.addFooterView(footer);
        footer.setVisibility(View.GONE);
        
        lvEvent.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true, new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (visibleItemCount+firstVisibleItem == totalItemCount&&totalItemCount!=0){
					if (listEvents == null) return;
					if(!isLoading&&!isLastPage){
						loadMore();
					}
				}
			}
		}));
        
        lvEvent.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int position,
					long id) {
				DataHolder.setEvent(listEvents.get(position));
				Intent intent=new Intent(getSherlockActivity(),DetailEventActivity.class);
				intent.putExtra("eventID", listEvents.get(position).getEventID());
				startActivity(intent);
			}
        	
		});
        
        btnRetry.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getData();
			}
		});
        
        if(listEvents == null) {
        	pageCount = 1;
        	isLastPage = false;
        	isLoading = false;
        	getData();
        }
        else setUpView();
        
        return rootView;
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	if (listEvents != null) for (Event e : listEvents) {
			if (e==DataHolder.getEvent()) e.setViewCount(e.getViewCount() + 1);
		}
    	if (adapter != null) adapter.notifyDataSetChanged();
    }
    
    private void setUpView(){
    	btnRetry.setVisibility(View.GONE);
    	prBar.setVisibility(View.GONE);
    	lvEvent.setVisibility(View.VISIBLE);
    	adapter = new EventAdapter(getSherlockActivity(), 1, listEvents);
    	
    	lvEvent.setAdapter(adapter);
    }
    
    
    private void getData() {
		if (NetworkUtility.checkNetworkState(getSherlockActivity())) {
			
			btnRetry.setVisibility(View.GONE);
	    	prBar.setVisibility(View.VISIBLE);
	    	lvEvent.setVisibility(View.GONE);
			
			NewRestConnector.post("", NewParamBuilder
					.BuildParams(NewParamBuilder.BuildEventData(1)),
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int arg0, String response) {
							if(response == null){
								btnRetry.setVisibility(View.VISIBLE);
						    	prBar.setVisibility(View.GONE);
						    	lvEvent.setVisibility(View.GONE);
								return;
							}
							super.onSuccess(arg0, response);
							if (NewResponseTranslater.checkSuccess(response)&&getSherlockActivity()!=null) {
								listEvents = NewResponseTranslater.getEvent(response);
								setUpView();
							} else {
								btnRetry.setVisibility(View.VISIBLE);
						    	prBar.setVisibility(View.GONE);
						    	lvEvent.setVisibility(View.GONE);
							}

						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							btnRetry.setVisibility(View.VISIBLE);
					    	prBar.setVisibility(View.GONE);
					    	lvEvent.setVisibility(View.GONE);
					    	super.onFailure(arg0, arg1);
						}
					});
		} else {
			btnRetry.setVisibility(View.VISIBLE);
	    	prBar.setVisibility(View.GONE);
	    	lvEvent.setVisibility(View.GONE);
	    	
			Toast.makeText(getSherlockActivity(), "Không có kết nối",
					Toast.LENGTH_SHORT).show();
		}
	}
    
    private void loadMore(){
    	if (NewNetworkUtility.checkNetworkState(getSherlockActivity())){
    		isLoading = true;
    		footer.setVisibility(View.VISIBLE);
    		RestConnector.post("", NewParamBuilder.BuildParams(NewParamBuilder.BuildEventData(pageCount+1)), new AsyncHttpResponseHandler(){
    			
    			@Override
    			public void onSuccess(int arg0, String response) {
    				footer.setVisibility(View.GONE);
    				if(response == null){
    					Util.showToast("Lỗi kết nối", getSherlockActivity(), Toast.LENGTH_SHORT);
    					isLoading = false;
    					return;
    				}
    				if(NewResponseTranslater.checkSuccess(response)){
    					ArrayList<Event> events = NewResponseTranslater.getEvent(response);
    					if (events.size()<1){
    						isLoading = false;
        					isLastPage = true;
        					Util.showToast("Không có dữ liệu mới", getSherlockActivity(), Toast.LENGTH_SHORT);
        					return;
    					}
    					listEvents.addAll(events);
    					adapter.setEventData(listEvents);
    					adapter.notifyDataSetChanged();
    					pageCount++;
    					isLoading = false;
    				} else {
    					isLoading = false;
    					isLastPage = true;
    					Util.showToast("Không có dữ liệu mới", getSherlockActivity(), Toast.LENGTH_SHORT);
    				}
    				super.onSuccess(arg0, response);
    			}
    			
    			@Override
    			public void onFailure(Throwable arg0, String arg1) {
    				super.onFailure(arg0, arg1);
    				isLoading = false;
					footer.setVisibility(View.GONE);
					Util.showToast("Lỗi kết nối", getSherlockActivity(), Toast.LENGTH_SHORT);
    			}
    			
    		});
    	} else {
    		footer.setVisibility(View.GONE);
    		Util.showToast("Không có kết nối", getSherlockActivity(), Toast.LENGTH_SHORT);
    	}
    }
 
}

